package fileoperation;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Scanner;

/*
1、注意与FileReader的区别,FileRead方法类为读取对象指针所指的下一个对象；
而FileReader为读取对象数据域内的内容
 */
public class FileRead {
    public static String readBranchFromHead(File head){
        try{
            String branch = FileReader.deserializeFileValue(head);
            return branch;
        }
        catch (Exception e){
            e.printStackTrace();
            return "";
        }
    }

    //读取分支中的commit节点
    public static String readCommitFromBranch(File branch){
        ArrayList<String> commitList =  new ArrayList<>();
        String commit = " ";
        try{
            String value = FileReader.deserializeFileValue(branch);
            //反序列化branch
            commitList = FileReader.readByBufferReader(value);
            if (commitList.size() != 0){//此处考虑commit为首次提交
                commit = commitList.get(0);
                //读取branch中第一个commit
            }
        }
        catch (Exception e){
            e.printStackTrace();
        }
        return commit;
    }

    //读取commit节点父指针
    public static String readParentFromCommit(File commit){
        try{
//            System.out.println("commit is " + commit.getAbsolutePath());
            Scanner in = new Scanner(commit);
            String line1 = in.nextLine();
            String line2 = in.nextLine();
            String[] line2Splited = line2.split("\\ ");
            String parent = line2Splited[1];
            in.close();
            if(parent.length()!=40){
                return "";
            }
            else{
                return parent;
            }
        }
        catch (Exception e){
//            e.printStackTrace();
            return "";
        }
    }

    //读取commit节点中的数据
    public static String readTreeFromCommit(File commit) throws Exception{
        try(Scanner in = new Scanner(commit)){
            while(in.hasNext()){
                String line = in.nextLine();
                String[] lineSplited = line.split(" ");
                String hashcode = lineSplited[1];
                return hashcode;
            }
        }
        return null;
    }
}
